package com.woniu.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.entity.PageData;
import com.woniu.entity.dto.QueryOrderInfoDTO;
import com.woniu.entity.vo.OrderInfoVo;
import com.woniu.enums.OrderStatus;
import com.woniu.mapper.OrderInfoMapper;
import com.woniu.mapper.ProductMapper;
import com.woniu.mapper.TrainingMapper;
import com.woniu.pojo.OrderInfo;
import com.woniu.pojo.Product;
import com.woniu.pojo.Training;
import com.woniu.service.OrderInfoService;
import com.woniu.util.OrderNoUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.Duration;
import java.time.Instant;
import java.util.List;

@Service
@Slf4j
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements OrderInfoService {

    @Resource
    private ProductMapper productMapper;

    @Resource
    private TrainingMapper trainingMapper;

    @Resource
    private OrderInfoMapper orderInfoMapper;

    @Override
    public OrderInfo createOrderByProductId(Long productId,Long userId, String paymentType) {

        //查找已存在但未支付的订单
        OrderInfo orderInfo = this.getNoPayOrderByProductId(productId, paymentType);
        if( orderInfo != null){
            return orderInfo;
        }


        //获取商品信息
        Product product = productMapper.selectById(productId);

        //生成订单
        if (productId < 10){
            orderInfo = new OrderInfo();
            orderInfo.setUserId(userId);
            orderInfo.setTitle(product.getTitle());
            orderInfo.setOrderNo(OrderNoUtils.getOrderNo(productId)); //订单号
            orderInfo.setProductId(productId);
            orderInfo.setTotalFee(product.getPrice()); //分
            orderInfo.setOrderStatus(OrderStatus.NOTPAY.getType()); //未支付
            orderInfo.setPaymentType(paymentType);
            baseMapper.insert(orderInfo);
        }else {
            Training training = trainingMapper.selectById(productId);

            orderInfo = new OrderInfo();
            orderInfo.setUserId(userId);
            orderInfo.setTitle(training.getTrainingName());
            orderInfo.setOrderNo(OrderNoUtils.getOrderNo(productId));
            orderInfo.setProductId(productId);
            orderInfo.setTotalFee(training.getPrice());
            orderInfo.setOrderStatus(OrderStatus.NOTPAY.getType()); //未支付
            orderInfo.setPaymentType(paymentType);
            baseMapper.insert(orderInfo);
        }

        return orderInfo;
    }

    /**
     * 存储订单二维码
     * @param orderNo
     * @param codeUrl
     */
    @Override
    public void saveCodeUrl(String orderNo, String codeUrl) {

        QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_no", orderNo);

        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setCodeUrl(codeUrl);

        baseMapper.update(orderInfo, queryWrapper);
    }

    /**
     * 查询订单列表，并倒序查询
     * @return
     */
    @Override
    public List<OrderInfo> listOrderByCreateTimeDesc() {

        QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<OrderInfo>().orderByDesc("create_time");
        return baseMapper.selectList(queryWrapper);
    }

    /**
     * 根据订单号更新订单状态
     * @param orderNo
     * @param orderStatus
     */
    @Override
    public void updateStatusByOrderNo(String orderNo, OrderStatus orderStatus) {

        log.info("更新订单状态 ===> {}", orderStatus.getType());

        QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_no", orderNo);

        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setOrderStatus(orderStatus.getType());

        baseMapper.update(orderInfo, queryWrapper);
    }

    /**
     * 根据订单号获取订单状态
     * @param orderNo
     * @return
     */
    @Override
    public String getOrderStatus(String orderNo) {

        QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_no", orderNo);
        OrderInfo orderInfo = baseMapper.selectOne(queryWrapper);
        if(orderInfo == null){
            return null;
        }
        return orderInfo.getOrderStatus();
    }

    /**
     * 查询创建超过minutes分钟并且未支付的订单
     * @param minutes
     * @return
     */
    @Override
    public List<OrderInfo> getNoPayOrderByDuration(int minutes, String paymentType) {

        Instant instant = Instant.now().minus(Duration.ofMinutes(minutes));

        QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_status", OrderStatus.NOTPAY.getType());
        queryWrapper.le("create_time", instant);
        queryWrapper.eq("payment_type", paymentType);

        List<OrderInfo> orderInfoList = baseMapper.selectList(queryWrapper);

        return orderInfoList;
    }

    /**
     * 根据订单号获取订单
     * @param orderNo
     * @return
     */
    @Override
    public OrderInfo getOrderByOrderNo(String orderNo) {

        QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_no", orderNo);
        OrderInfo orderInfo = baseMapper.selectOne(queryWrapper);

        return orderInfo;
    }


    @Override
    public List<OrderInfoVo> listInfo() {
        return orderInfoMapper.listInfo();
    }

    @Override
    public PageData searchPage(Integer currentPage, Integer pageSize, QueryOrderInfoDTO queryOrderDTO) {
        IPage<OrderInfoVo> page = new Page<>(currentPage, pageSize);
        IPage<OrderInfoVo> searchPage = orderInfoMapper.searchPage(page, queryOrderDTO);
        PageData pageData = new PageData(searchPage.getTotal(), searchPage.getRecords());
        return pageData;
    }


    /**
     * 根据商品id查询未支付订单
     * 防止重复创建订单对象
     * @param productId
     * @return
     */
    private OrderInfo getNoPayOrderByProductId(Long productId, String paymentType) {

        QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("product_id", productId);
        queryWrapper.eq("order_status", OrderStatus.NOTPAY.getType());
        queryWrapper.eq("payment_type", paymentType);
//        queryWrapper.eq("user_id", userId);
        OrderInfo orderInfo = baseMapper.selectOne(queryWrapper);
        return orderInfo;
    }
// 查询用户是否买过该靶场
    @Override
    public boolean selectOrder(Integer userId, Integer trainingId) {
           QueryWrapper<OrderInfo> wrapper = new QueryWrapper<>();
           wrapper.eq("user_id", userId);
           List<OrderInfo> list = baseMapper.selectList(wrapper);
           if (list != null){
               for (OrderInfo info :list) {
                   String[] split = info.getOrderNo().split("_");
                   String tid = split[1];
                   if (tid.equals(String.valueOf(trainingId)) && info.getOrderStatus().equals("支付成功")){

                       return true;
                   }
               }
           }


        return false;
    }
}
